const db = require("./db.js");
exports.login = (req,res) => {
    let username = req.body.username;
    let pwd = req.body.password;

    //获取 前端传过来的用户名和密码
    let sql = "select * from Users where Username = ?";
    db.base(sql,username,(result,err) =>{
        if(!result.length){
            return res.json({status:0,msg:'用户名错误'});
        }else{
            if(result[0].pwd == pwd){
                return res.json({status:1,msg:'登录成功！',data:result});
            }
            return res.json({status:2,msg:'密码错误'});
        }
    })
}

//注册 todo 用户信息验证->正则表达式
exports.register = (req,res) =>{
    let username = req.body.username;
    let pwd = req.body.password;
    let sql = "insert into Users(Username,PASSWORD) values(?,?)";
    try{
        db.base(sql,[Username,PASSWORD],(result,err) =>{
            if(err){
                console.log(err);
                return res.json({status:0,msg:err});
            }else{
                return res.json({status:1,msg:'注册成功！'});
            }
        })
    } catch(error){
        console.log(error);
    }
}

//商城首页
exports.index = (req,res) =>{
    let sql = "select * from Products";
    let a = "";
    //函数的调用需要传参，所以定义一个空的变量
    try{
        db.base(sql,a,(result,err) =>{
            if(err){
                console.log(err);
                console.log("商品信息读取失败");
                return res.json({status:0,msg:'商品信息读取失败'});
            }else{
                return res.json({status:1,msg:'商品信息读取成功',data:result});
            }
        })
    }catch(error){
        console.log(error);
    }

}